import React, { Component } from 'react'
import { Form, Upload } from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import styles from './ImageUpload.module.css'

export default class ImageUpload extends Component {
  static defaultProps = { // 自定义属性的默认值
    required: true, // 默认为必传
  };

  state={
    imageUrl:this.props.defaultUrl
  }

  onSuccess = (res) => {
    // 文件上传成功的回调
    if (res.file.xhr) {
      // 上传成功返回
      const data = JSON.parse(res.file.xhr.responseText)
      if (data.success) {
        this.setState({ imageUrl: data.result.url }) // 设置图片地址
      }
    }
  }

  render() {
    const rules = []
    const {imageUrl} = this.state
    const  {
      label, // 标签
      name, // 字段
      required, // 是否必传
    } = this.props;
    if (required) {
      rules.push({ required, message: '请上传' + label });
    } 
    return (
      <div>
        <Form.Item label={label} name={name}>
          <Upload
            name='file'
            listType='picture-card'
            showUploadList={false}
            action='/api/upload'
            onChange={this.onSuccess}
          >
            {imageUrl ? (
              <img className={styles.head1} src={imageUrl}  alt='图片'/>
            ) : (
              <PlusOutlined />
            )}
          </Upload>
        </Form.Item>
      </div>
    )
  }
}
